/*
提交链接：https://leetcode.cn/problems/count-complete-tree-nodes/
222. 完全二叉树的节点个数
赖德檀 2024/9/17
*/

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:

TreeNode* test(TreeNode *root,int k)
{
    if(root==NULL) return NULL;
    if(k==1) return root;
    TreeNode* p= test(root,k/2);
    if(p==NULL) return NULL;
    if(k==k/2*2)
    return p->left;
    else
    return p->right;
}

    int countNodes(TreeNode* root) {
        if(root==NULL) return 0;
        int l=0,r=50000;
        while(l<r)
        {
            int mid=(r+l+1)/2;
            TreeNode* p=test(root,mid);
            if(!p)
            r=mid-1;
            else
            l=mid;
        }
        return l;
    }
};